// 数据管理工具，模拟后端API

class DataManager {
  constructor() {
    this.data = {
      users: [
        {
          id: 1,
          username: 'teacher1',
          password: '123456',
          name: '张教授',
          role: 'teacher',
          enrolledCourses: []
        },
        {
          id: 2,
          username: 'teacher2',
          password: '123456',
          name: '李老师',
          role: 'teacher',
          enrolledCourses: []
        },
        {
          id: 3,
          username: 'student1',
          password: '123456',
          name: '王同学',
          role: 'student',
          enrolledCourses: []
        },
        {
          id: 4,
          username: 'student2',
          password: '123456',
          name: '刘同学',
          role: 'student',
          enrolledCourses: []
        },
        {
          id: 5,
          username: 'student3',
          password: '123456',
          name: '陈同学',
          role: 'student',
          enrolledCourses: []
        }
      ],
      courses: [
        {
          id: 1,
          title: 'Web前端开发',
          description: '学习HTML、CSS、JavaScript等前端技术',
          teacher: '张教授',
          capacity: 30,
          enrolled: 15,
          schedule: '周一 14:00-16:00',
          status: 'open'
        },
        {
          id: 2,
          title: '数据结构',
          description: '学习各种数据结构和算法',
          teacher: '李老师',
          capacity: 25,
          enrolled: 25,
          schedule: '周三 10:00-12:00',
          status: 'full'
        },
        {
          id: 3,
          title: '数据库原理',
          description: '学习关系型数据库设计和SQL语言',
          teacher: '张教授',
          capacity: 20,
          enrolled: 8,
          schedule: '周五 08:00-10:00',
          status: 'open'
        }
      ]
    }
    this.loadData()
  }

  // 从localStorage加载数据（如果有的话）
  loadData() {
    const storedData = localStorage.getItem('course_system_data')
    if (storedData) {
      this.data = JSON.parse(storedData)
    } else {
      // 首次使用，保存初始数据
      this.saveData()
    }
  }

  // 保存数据到localStorage
  saveData() {
    localStorage.setItem('course_system_data', JSON.stringify(this.data))
  }

  // 获取所有用户
  getUsers() {
    return this.data.users
  }

  // 获取所有课程
  getCourses() {
    return this.data.courses
  }

  // 根据用户名获取用户
  getUserByUsername(username) {
    return this.data.users.find(user => user.username === username)
  }

  // 验证用户登录
  validateUser(username, password) {
    const user = this.getUserByUsername(username)
    return user && user.password === password ? user : null
  }

  // 添加新课程
  addCourse(courseData) {
    const newCourse = {
      id: Date.now(),
      ...courseData,
      enrolled: 0,
      status: 'open'
    }
    this.data.courses.push(newCourse)
    this.saveData()
    return newCourse
  }

  // 更新课程
  updateCourse(courseId, updates) {
    const index = this.data.courses.findIndex(c => c.id === courseId)
    if (index !== -1) {
      this.data.courses[index] = { ...this.data.courses[index], ...updates }
      this.saveData()
      return this.data.courses[index]
    }
    return null
  }

  // 删除课程
  deleteCourse(courseId) {
    const index = this.data.courses.findIndex(c => c.id === courseId)
    if (index !== -1) {
      this.data.courses.splice(index, 1)
      this.saveData()
      return true
    }
    return false
  }

  // 学生选课
  enrollStudent(courseId, studentId) {
    const course = this.data.courses.find(c => c.id === courseId)
    if (course && course.enrolled < course.capacity && course.status === 'open') {
      course.enrolled++
      if (course.enrolled >= course.capacity) {
        course.status = 'full'
      }
      
      // 更新用户选课记录
      const user = this.data.users.find(u => u.id === studentId)
      if (user && user.role === 'student') {
        if (!user.enrolledCourses) {
          user.enrolledCourses = []
        }
        if (!user.enrolledCourses.includes(courseId)) {
          user.enrolledCourses.push(courseId)
        }
      }
      
      this.saveData()
      return true
    }
    return false
  }

  // 学生退课
  dropCourse(courseId, studentId) {
    const course = this.data.courses.find(c => c.id === courseId)
    const user = this.data.users.find(u => u.id === studentId)
    
    if (course && user && user.role === 'student' && user.enrolledCourses) {
      const courseIndex = user.enrolledCourses.indexOf(courseId)
      if (courseIndex > -1) {
        user.enrolledCourses.splice(courseIndex, 1)
        course.enrolled--
        course.status = 'open'
        this.saveData()
        return true
      }
    }
    return false
  }

  // 获取用户已选课程ID列表
  getUserEnrolledCourses(userId) {
    const user = this.data.users.find(u => u.id === userId)
    return user && user.enrolledCourses ? user.enrolledCourses : []
  }

  // 根据教师名称获取课程
  getCoursesByTeacher(teacherName) {
    return this.data.courses.filter(c => c.teacher === teacherName)
  }

  // 获取可选课程（未满员且状态为open）
  getAvailableCourses() {
    return this.data.courses.filter(c => c.status === 'open')
  }

  // 根据ID获取课程
  getCourseById(courseId) {
    return this.data.courses.find(c => c.id === courseId)
  }

  // 重置数据到初始状态
  resetData() {
    this.data = {
      users: [
        {
          id: 1,
          username: 'teacher1',
          password: '123456',
          name: '张教授',
          role: 'teacher',
          enrolledCourses: []
        },
        {
          id: 2,
          username: 'teacher2',
          password: '123456',
          name: '李老师',
          role: 'teacher',
          enrolledCourses: []
        },
        {
          id: 3,
          username: 'student1',
          password: '123456',
          name: '王同学',
          role: 'student',
          enrolledCourses: []
        },
        {
          id: 4,
          username: 'student2',
          password: '123456',
          name: '刘同学',
          role: 'student',
          enrolledCourses: []
        },
        {
          id: 5,
          username: 'student3',
          password: '123456',
          name: '陈同学',
          role: 'student',
          enrolledCourses: []
        }
      ],
      courses: [
        {
          id: 1,
          title: 'Web前端开发',
          description: '学习HTML、CSS、JavaScript等前端技术',
          teacher: '张教授',
          capacity: 30,
          enrolled: 15,
          schedule: '周一 14:00-16:00',
          status: 'open'
        },
        {
          id: 2,
          title: '数据结构',
          description: '学习各种数据结构和算法',
          teacher: '李老师',
          capacity: 25,
          enrolled: 25,
          schedule: '周三 10:00-12:00',
          status: 'full'
        },
        {
          id: 3,
          title: '数据库原理',
          description: '学习关系型数据库设计和SQL语言',
          teacher: '张教授',
          capacity: 20,
          enrolled: 8,
          schedule: '周五 08:00-10:00',
          status: 'open'
        }
      ]
    }
    this.saveData()
  }
}

// 创建单例实例
export const dataManager = new DataManager()

export default dataManager